package com.cg.asm.core.service.user.impl;

import com.cg.asm.core.dao.user.UserMapper;
import com.cg.asm.core.domain.vo.user.UserLoginVO;
import com.cg.asm.core.domain.vo.user.UserUpPwdVO;
import com.cg.asm.core.exception.AccountLockException;
import com.cg.asm.core.service.user.IUserInfoService;
import com.cg.asm.client.DateUtil;
import com.cg.asm.client.exception.AsmException;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import java.util.List;

@Service
@EnableTransactionManagement(proxyTargetClass = true)
public class UserInfoService implements IUserInfoService, UserDetailsService {

    @Resource
    private UserMapper userMapper;
    // 总控平台配置信息
    @Value("${asm.config.maxErrorLoginNumber}")
    private Integer maxErrorLoginNumber;

    /**
     * 获取用户登录信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        UserLoginVO userInfoDTO = userMapper.loadLoginUserByUsername(username);
        if (userInfoDTO == null) {
            throw new UsernameNotFoundException("【后台信息】登录失败，用户名称不存在!");
        } else {
            // 如果当前日期 等于 锁定日期，则比较错误次数，大于最大错误次数则禁止登陆
            if (DateUtil.getDate("yyyy-MM-dd").equals(userInfoDTO.getLockDate())) {
                if (null != maxErrorLoginNumber && null != userInfoDTO.getErrorLoginNumber()) {
                    if (userInfoDTO.getErrorLoginNumber() >= maxErrorLoginNumber) {
                        throw new AccountLockException("【后台信息】登录失败，次数超限");
                    }
                }
            }
            List<String> roleIds = userMapper.getUserRolesId(userInfoDTO.getUserId(), userInfoDTO.getUserGroupId());
            if (null != roleIds && roleIds.size() != 0) {
                userInfoDTO.setRoles(roleIds);
                userInfoDTO.setUserPoints(userMapper.getUserFunPoints(userInfoDTO.getUserId()));
            }
        }
        return userInfoDTO;
    }

    /**
     * 用户修改密码
     *
     * @param userUpPwdVO
     */
    @Override
    public void updatePWD(UserUpPwdVO userUpPwdVO) {
        if (null != userUpPwdVO && StringUtil.isNotEmpty(userUpPwdVO.getUserId())) {
            String oldPwd = userMapper.getPwdByUserId(userUpPwdVO.getUserId());
            BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
            boolean compareResult = bpe.matches(userUpPwdVO.getOldPassword(), oldPwd);
            if (compareResult) {
                if (StringUtil.isNotEmpty(userUpPwdVO.getNewPassword())) {
                    String encoderPwd = bpe.encode(userUpPwdVO.getNewPassword());
                    userMapper.updateUserPwd(encoderPwd, userUpPwdVO.getUserId());
                } else {
                    throw new AsmException("密码修改失败，新密码不能为空!");
                }
            } else {
                throw new AsmException("密码修改失败，原密码不正确!");
            }
        } else {
            throw new AsmException("密码修改失败，用户Id不能为空!");
        }
    }
}
